<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
//实例化极光推送


/**
 * 返回规定分隔符的日期
 * @param $timestamp 时间戳
 * @param string $symbol 分隔符
 * @return false|string
 */
function conversionDate($timestamp, $symbol = "-")
{
    return date("Y" . $symbol . "m" . $symbol . "d", $timestamp);
}

/**
 * 返回元
 * @param $value 分
 * @return float|int
 */
function convertRmb($value)
{
    return $value / 100;
}

/**
 * 发送短信
 * @param $tel String 手机号
 * @param $tpl string 短信模板
 * @param $data array 短信数据
 * @return array
 */
function sendSms($tel, $tpl, $data)
{
    //这里的路径EXTEND_PATH就是指tp5根目录下的extend目录，系统自带常量。alisms为我们复制api_sdk过来后更改的目录名称
    require_once EXTEND_PATH . 'alisms/vendor/autoload.php';
    \Aliyun\Core\Config::load();             //加载区域结点配置
    $accessKeyId = config("ALI_VCODE.key");  //阿里云短信获取的accessKeyId
    $accessKeySecret = config("ALI_VCODE.secret"); //阿里云短信获取的accessKeySecret
    //这个个是审核过的模板内容中的变量赋值，记住数组中字符串code要和模板内容中的保持一致
    //比如我们模板中的内容为：你的验证码为：${code}，该验证码5分钟内有效，请勿泄漏！
    $templateParam = $data;           //模板变量替换
    $signName = config("ALI_VCODE.sign_name"); //这个是短信签名，要审核通过
    $templateCode = $tpl;   //短信模板ID，记得要审核通过的
    //短信API产品名（短信产品名固定，无需修改）
    $product = "Dysmsapi";
    //短信API产品域名（接口地址固定，无需修改）
    $domain = "dysmsapi.aliyuncs.com";
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
    $region = "cn-hangzhou";
    // 初始化用户Profile实例
    $profile = \Aliyun\Core\Profile\DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
    // 增加服务结点
    \Aliyun\Core\Profile\DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    // 初始化AcsClient用于发起请求
    $acsClient = new \Aliyun\Core\DefaultAcsClient($profile);
    // 初始化SendSmsRequest实例用于设置发送短信的参数
    $request = new \Aliyun\Api\Sms\Request\V20170525\SendSmsRequest();
    // 必填，设置雉短信接收号码
    $request->setPhoneNumbers($tel);
    // 必填，设置签名名称
    $request->setSignName($signName);
    // 必填，设置模板CODE
    $request->setTemplateCode($templateCode);
    // 可选，设置模板参数
    if ($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }
    //发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);
    //返回请求结果
    $result = json_decode(json_encode($acsResponse), true);
    if ($result["Code"] == "OK") {
        return array(
            "result" => true,
            "message" => ""
        );
    } else {
        return array(
            "result" => false,
            "message" => $result["Message"]
        );
    }
}

/**
 * 验证手机号
 */
function checkTelFormat($phoneNumber)
{
    $pattern = "/^1[3456789]\d{9}$/";
    $phoneStatus = preg_match($pattern, $phoneNumber);
    if ($phoneStatus == 1) {
        return true;
    } else {
        return false;
    }
}

/**
 * 获取当前时间
 */
function getTime()
{
    return date("Y-m-d H:i:s");
}

/**
 * 检测文件或目录是否存在
 * @param string $dir
 * @return boolean
 */
function isFileDir($dir)
{
    if (!file_exists($dir)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 创建目录
 * @param string $dir
 * @return boolean
 */
function establish($dir)
{
    $result = mkdir($dir, 0777, true);
    if ($result) {
        return true;
    } else {
        return false;
    }
}

//单个文件上传
function uploadFile($file, $user_id, $img_path)
{
    $path = $img_path ? $img_path : config("USER_HEAD_IMAGE") . $user_id . "/";
    if (!isFileDir($path)) if (!establish($path)) return false;
    $result = [];
    if ($file) {
        $info = $file->validate(config("UPLOAD_CONFIG"))->move($path);
        if ($info) {
            $Name = $info->getSaveName();
            $result["result"] = true;
            $result["path"] = $path . $Name;
        } else {
            // 上传失败获取错误信息
            $result["result"] = false;
            $result["path"] = $file->getError();
        }
    }
    return $result;
}

//返回订单编号
function getOrderNo()
{
    $rand = rand(1000, 9999);
    return "A" . date("YmdHis") . $rand;
}

//返回随机字符串
function sessionStr()
{
    return rand(1000, 9999) . date('YmdHis') . 'spyxcx';
}

/*写文件*/
function writeLog($pay_type, $content)
{
    $mk = ROOT_PATH . 'pay_log/';
    $filename = $mk . $pay_type . date('Y-m-d') . '.txt';
    if (!isFileDir($mk)) if (!establish($mk)) return false;
    $string = "执行日期：" . "\r\n" . date('Y-m-d H:i:s', time()) . ' ' . "\n" . $content . "\n";
    file_put_contents($filename, $string, FILE_APPEND);
}

/**
 * 图片转移
 * @param string $path 文件路径
 * @param string $newPath 新文件路径
 * @return path
 */
function moveFile($path, $newPath)
{
    $domain = config("HTTP_DOMAIN_NAME");
    if (!file_exists($path)) return false;
    if (!is_file($path)) return false;
    if (!isFileDir($newPath)) {
        if (!establish($newPath)) {
            return false;
        }
    }
    $file_name = basename($path);
    if (!rename($path, $newPath . $file_name)) return false;
    return $domain . $newPath . $file_name;
}

/**
 * 获取文件名称
 * @param $string
 * @return mixed
 */
function getFileName($string)
{
    $array = explode("/", $string);
    $em = count($array) - 1;
    return $array[$em];
}

//正数和小数点后两位
function verifyNum($value)
{
    $pattern = "/^([1-9]\d*|0)(\.\d{1,2})?$/";
    $phoneStatus = preg_match($pattern, $value);
    if ($phoneStatus == 1) {
        return true;
    } else {
        return false;
    }
}

//url验证
function verifyUrl($value)
{
    $pattern = '/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/';
    $phoneStatus = preg_match($pattern, $value);
    if ($phoneStatus == 1) {
        return true;
    } else {
        return false;
    }
}

//返回目标
function goal($arr)
{
    return "," . implode(",", $arr) . ",";
}

/*
 * 返回utf8表文字
 */
function getUtf8($font)
{
    return iconv('utf-8', 'GB2312//IGNORE', $font);
}

/**
 * @return string
 */
function str_randoms()
{
    return date("YmdHis") . time() . rand(100000, 999999);
}

function getAddress($longitude, $latitude)
{
    $url = "http://restapi.amap.com/v3/geocode/regeo?output=json&location=" . $longitude . ',' . $latitude . "&key=d76a846aa32a0dfd9a58e788b16bdc74";
    if ($result = file_get_contents($url)) {
        $result = json_decode($result, true);
        if (!empty($result['status']) && $result['status'] == 1) {
            return $result['regeocode']['formatted_address'];
        } else {
            return false;
        }
    }
}

function getDistance($store, $from)
{
    foreach ($store as $k => $v) {
        $destination = $store[$k]['longitude'] . ',' . $store[$k]['dimensions'];
        $origins = $from[0] . ',' . $from[1];
        $app = "http://restapi.amap.com/v3/distance?origins=$origins&destination=$destination&output=JSON&type=0&key=409b460dc7afa24c9a18db0ee0e0dfdc";
        $Service = file_get_contents($app);
        $Service = json_decode($Service, true);
        if ($Service['status'] != 1) return false;
        foreach ($Service['results'] as $key => $val) {
            $store[$k]['distance'] = $val['distance'];
        }
    }
    return $store;
}

function wxMoveFile($path, $newPath)
{
    if (!file_exists($path)) return false;
    if (!is_file($path)) return false;
    if (!isFileDir($newPath)) {
        if (!establish($newPath)) {
            return false;
        }
    }
    $file_name = basename($path);
    if (!rename($path, $newPath . $file_name)) return false;
    return $newPath . $file_name;
}

function gPic_Url($content)
{
    $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";//正则
    preg_match_all($pattern, $content, $match);//匹配图片
    return $match[1];//返回所有图片的路径
}

//违章查询
function getWz($appkey, $city, $carno, $engineno, $classno)
{
    header('Content-type:text/html;charset=utf-8');
    require_once ROOT_PATH . '/extend/juheapi/wz.php';
    // $appkey = '9c9bc8efdd768fda65113d3ee2dbd8db'; //您申请的违章查询key
    $wz = new wz($appkey);
    // $wzcitys = $wz->getCitys(); //查询所有的支持城市
    // $wzcitys = $wz->getCitys('HB'); //查询指定省份下的城市
    //$city = 'HB_SJZ'; //城市代码，必传
    //$carno = '粤S*****'; //车牌号，必传
    //$engineno = '****'; //发动机号，需要的城市必传
    //$classno = '*****'; //车架号，需要的城市必传
    $wzResult = $wz->query($city, $carno, $engineno, $classno);
    if ($wzResult['error_code'] == 0) {
        if ($wzResult['result']['lists']) {
            foreach ($wzResult['result']['lists'] as $key => $w) {
                //以下就是根据实际业务需求修改了
                $data = $w['area'] . " " . $w['date'] . " " . $w['act'];
            }
        } else {
            $data = "该车无违章记录";
        }
    } else {
        //查询不成功
        $data = "查询出错了~";
    }
    return $data;
}

//门店编辑
function storeEdit($is_store, $data)
{
    $list['data'] = $data;
    if ($is_store == 1) {
        $admin_id = session('admin_id');
        $store_id = model('Store')->getStoreId($admin_id);
        foreach ($list['data'] as $k => $v) {
            if ($list['data'][$k]['location_store_id'] == $store_id) {
                $list['data'][$k]['is_edit'] = 1;
            } else {
                $list['data'][$k]['is_edit'] = 2;
            }
        }
    } else {
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['is_edit'] = 1;
        }
    }
    return $list['data'];
}